package org.platform.tool.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.digester.Digester;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * 读取配置文件的工具类
 * 
 * @author mabb
 */
@Slf4j
public class ResourceUtils {
    /**
     * 获取资源的路径
     * 
     * @param path
     * @return
     */
    public static Resource fetchResourceFrom(String path) {
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource res = resolver.getResource(path);

	return res;
    }

    /**
     * 读取资源文件
     * 
     * @param strFilePath
     * @return
     */
    public static Properties readFromResource(String strFilePath) {
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource res = resolver.getResource(strFilePath);

	InputStream in = null;
	Properties props = new Properties();
	try {
	    in = res.getInputStream();
	    String filename = res.getFilename();
	    if (filename.endsWith(".xml")) {
		props.loadFromXML(in);
	    } else {
		props.load(in);
	    }
	    return props;
	} catch (IOException e) {
	    return props;
	} finally {
	    IOUtils.closeQuietly(in);
	}
    }

    /**
     * 读取XML对象
     * 
     * @param ruleUrl
     * @param objUrl
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> readEntityListFromXML(final URL ruleUrl, final URL objUrl) {
	if (null == objUrl || null == ruleUrl)
	    return null;

	try {
	    Digester digester = org.apache.commons.digester.xmlrules.DigesterLoader.createDigester(ruleUrl);
	    List<T> result = new ArrayList<T>();
	    result = (List<T>) digester.parse(objUrl);

	    if (CollectionUtils.isEmpty(result)) {
		return Collections.emptyList();
	    }

	    CollectionUtils.collect(result, new Transformer() {
		@Override
		public Object transform(Object o) {
            return o;
		}
	    });
	    return result;
    } catch (Exception e) {
        log.error("异常: ", e);
    }
	return null;
    }

}
